package com.neuedu.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neuedu.entity.UserAnswer;
import com.neuedu.entity.UserAnswerItem;
import com.neuedu.mapper.UserAnswerMapper;
import com.neuedu.service.QuestionsService;
import com.neuedu.service.UserAnswerItemService;
import com.neuedu.service.UserAnswerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * <p>
 * 用户答题统计表 服务实现类
 * </p>
 *
 * @author wangyu
 * @since 2025-09-17
 */
@Service
public class UserAnswerServiceImpl extends ServiceImpl<UserAnswerMapper, UserAnswer> implements UserAnswerService {
    @Resource
    UserAnswerItemService userAnswerItemService;
    @Override
    @Transactional
    public boolean save(String content, Long login_id) {
        List<UserAnswerItem> userAnswerItems = JSON.parseArray(content, UserAnswerItem.class);
        UserAnswer userAnswer = new UserAnswer();
        userAnswer.setTotal(userAnswerItems.size());
        int correctCount = 0;
        for (UserAnswerItem userAnswerItem : userAnswerItems) {
            if ("简答".equals(userAnswerItem.getQuestionType())) {
                userAnswerItem.setActive(2);
                continue;
            }
            if (userAnswerItem.getCorrectAnswer().equals(userAnswerItem.getAnswer())) {
                userAnswerItem.setActive(1);
                correctCount++;
            } else {
                userAnswerItem.setActive(0);
            }
        }
        userAnswer.setCorrectCount(correctCount);
        userAnswer.setAccuracy(new BigDecimal(correctCount / userAnswerItems.size()));
        userAnswer.setUserId(login_id);
        userAnswer.setCreateDate(LocalDate.now());
        userAnswer.setCreateTime(LocalTime.now());
        userAnswer.setItems(content);
        return this.save(userAnswer);
    }

    @Override
    public List<UserAnswer> getAnswer(Long login_id) {
        QueryWrapper<UserAnswer> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", login_id)
                .orderByDesc("id");
        return this.list(wrapper);
    }
}
